<?php

namespace App\Services;

use App\Models\AgentConfig;
use Illuminate\Support\Arr;
use Overtrue\EasySms\EasySms;
use Overtrue\EasySms\Exceptions\NoGatewayAvailableException;

class SmsService
{
    public function sendVerifyCode($agentId, $mobile, $code)
    {
        $agentConfigs = AgentConfig::listConfigsByAgentId($agentId);
        $smsConfig = $this->getSmsConfig($agentConfigs);
        $easySms = new EasySms($smsConfig);

        try {
            $easySms->send($mobile, [
                'template' => Arr::get($agentConfigs, AgentConfig::VERIFY_CODE_TEMPLATE),
                'data' => [
                    'code' => $code,
                ],
            ]);
        } catch (NoGatewayAvailableException $e) {
            throw new \Exception($e->getLastException()->getMessage());
        }
    }

    private function getSmsConfig($agentConfigs)
    {
        return [
            // HTTP 请求的超时时间（秒）
            'timeout' => 5.0,
            // 默认发送配置
            'default' => [
                // 网关调用策略，默认：顺序调用
                'strategy' => \Overtrue\EasySms\Strategies\OrderStrategy::class,
                // 默认可用的发送网关
                'gateways' => ['aliyun'],
            ],
            // 可用的网关配置
            'gateways' => [
                'aliyun' => [
                    'access_key_id' => Arr::get($agentConfigs, AgentConfig::ALI_ACCESS_KEY_ID),
                    'access_key_secret' => Arr::get($agentConfigs, AgentConfig::ALI_ACCESS_KEY_SECRET),
                    'sign_name' => Arr::get($agentConfigs, AgentConfig::SMS_SIGN_NAME),
                ],
            ],
        ];
    }
}
